﻿using System;
using UnityEditor;
using UnityEngine;

namespace Nirvana
{
    /// <summary>
    /// UI置灰
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Effects/Gray Scale")]
    [RequireComponent(typeof(UIMaterialEffect))]
    [DisallowMultipleComponent]
    [ExecuteInEditMode]
    public sealed class UIGrayscale : MonoBehaviour
    {
        [Range(0f, 255f)]
        [SerializeField]
        private int graylerp;

        private UIMaterialEffect _uimaterialeffect;

        public int GrayLerp
        {
            get
            {
                return this.graylerp;
            }
            set
            {
                if (this.graylerp != value)
                {
                    this.graylerp = value;
                    this.Refresh();
                }
            }
        }

        void Awake()
        {
            Refresh();
        }

        void OnDestroy()
        {
            if (this._uimaterialeffect != null)
            {
                MaterialsEffect matEff = this._uimaterialeffect.MaterialsEffect;
                matEff.graylerp = 0;
                this._uimaterialeffect.MaterialsEffect=matEff;
                this._uimaterialeffect.Save();
            }
        }

#if UNITY_EDITOR
        private void OnValidate()
        {
            this.Refresh();
        }
#endif
        private void Refresh()
        {
#if UNITY_EDITOR
            PrefabType prefabType = PrefabUtility.GetPrefabType(gameObject);
            if (prefabType == PrefabType.Prefab)
            {
                return;
            }
            if (this._uimaterialeffect == null)
            {
                this._uimaterialeffect = this.GetOrAddComponent<UIMaterialEffect>();
            }
            MaterialsEffect matEff = this._uimaterialeffect.MaterialsEffect;
            matEff.graylerp = this.GrayLerp;
            this._uimaterialeffect.MaterialsEffect = matEff;
            this._uimaterialeffect.Save();
#else
            if (this._uimaterialeffect == null)
            {
                this._uimaterialeffect = this.GetOrAddComponent<UIMaterialEffect>();
            }
            MaterialsEffect matEff = this._uimaterialeffect.MaterialsEffect;
            matEff.graylerp = this.GrayLerp;
            this._uimaterialeffect.MaterialsEffect = matEff;
            this._uimaterialeffect.Save();
#endif
        }
    }
}
